# _*_ coding:utf-8 _*_
""" 
@Time: 2021/12/30 17:12
@User: zhwang48
"""
import base64
from datetime import datetime
import datetime
import hashlib
import hmac
import json, os
import time
from urllib.parse import urlencode

import requests


class AssembleHeaderException(Exception):
    def __init__(self, msg):
        self.message = msg


class Url:
    def __init__(this, host, path, schema):
        this.host = host
        this.path = path
        this.schema = schema
        pass


# calculate sha256 and encode to base64
def sha256base64(data):
    sha256 = hashlib.sha256()
    sha256.update(data)
    digest = base64.b64encode(sha256.digest()).decode(encoding='utf-8')
    return digest


def parse_url(requset_url):
    stidx = requset_url.index("://")
    host = requset_url[stidx + 3:]
    schema = requset_url[:stidx + 3]
    edidx = host.index("/")
    if edidx <= 0:
        raise AssembleHeaderException("invalid request url:" + requset_url)
    path = host[edidx:]
    host = host[:edidx]
    u = Url(host, path, schema)
    return u


# build websocket auth request url
def assemble_ws_auth_url(requset_url, method="POST", api_key="", api_secret=""):
    u = parse_url(requset_url)
    host = u.host
    path = u.path
    # now = datetime.now()
    # date = format_date_time(time.mktime(now.timetuple()))
    # print(date)
    # date = "Thu, 12 Dec 2019 01:57:27 GMT"

    date = datetime.datetime.now(datetime.timezone.utc).strftime('%a, %d %b %Y %H:%M:%S GMT')
    signature_origin = "host: {}\ndate: {}\n{} {} HTTP/1.1".format(host, date, method, path)
    # print(signature_origin)
    signature_sha = hmac.new(api_secret.encode('utf-8'), signature_origin.encode('utf-8'),
                             digestmod=hashlib.sha256).digest()
    signature_sha = base64.b64encode(signature_sha).decode(encoding='utf-8')
    authorization_origin = "api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"" % (
        api_key, "hmac-sha256", "host date request-line", signature_sha)
    authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8')
    # print(authorization_origin)
    values = {
        "host": host,
        "date": date,
        "authorization": authorization
    }

    return requset_url + "?" + urlencode(values)


def invoice_util(path):
    APIKey = "3ad055e0de46fa9ebf5afe0df94225a8"
    APPId = "31081998"
    APISecret = "M2MwYjcxMzEwOWVhNjA3MzNiN2U5ZDhl"
    # path = "D://test.png"
    w = open(path, 'rb')
    t = base64.b64encode(w.read())

    # url = 'https://iflydigita.api.xf-yun.com/v1/private/se9b136aa'
    url = 'http://iflydigita.api.xf-yun.com/v1/private/se9b136aa'

    body = {
        "header": {
            "app_id": APPId,
            "uid": "3976979589",
            "did": "SR08232194000020",
            "imei": "866402031869366",
            "imsi": "460026495272910",
            "mac": "6c:92:bf:65:c6:14",
            "net_type": "wifi",
            "net_isp": "CMCC",
            "status": 3,
            "request_id": ""
        },
        "parameter": {
            "se9b136aa": {
                "result": {
                    "encoding": "utf8",
                    "compress": "raw",
                    "format": "json"
                }
            }
        },
        "payload": {
            "default_request_data_1": {
                "encoding": "png",
                "image": str(t, 'UTF-8'),
                "status": 3
            }
        }
    }

    request_url = assemble_ws_auth_url(url, "POST", APIKey, APISecret)

    headers = {'content-type': "application/json", 'host': 'api.xf-yun.com', 'app_id': APPId}
    # print(request_url)
    # print(json.dumps(body))
    response = requests.post(request_url, data=json.dumps(body), headers=headers)
    # print(response.json())
    st = response.json().get('payload').get('result').get('text')
    result = base64.b64decode(st).decode('utf-8')
    # print(result)
    # print(json.dumps(result,ensure_ascii=False))
    result = json.loads(result).get('response').get('data').get('identify_results')[0].get('details')
    # print(result)
    w.close()
    return result

def format_date_time(timestamp):
    _weekdayname = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
    _monthname = [None,  # Dummy so we can use 1-based month numbers
                  "Jan", "Feb", "Mar", "Apr", "May", "Jun",
                  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
    year, month, day, hh, mm, ss, wd, y, z = time.gmtime(timestamp)
    return "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
        _weekdayname[wd], day, _monthname[month], year, hh, mm, ss
    )
def main(*args, **kwargs):
    """
    必须写main函数
    :param args: 参数用数字接收
    :param kwargs: 参数用字典接收
    :return: 拿studio的返回值接收main函数的返回值
    """
    print(kwargs.get('para1'))
    # filePath = "D:\\test"
    # for a, b, c in os.walk(filePath):
    #     for i in range(len(c)):
    #         fp_path = os.path.join(filePath, c[i])
    #         result = invoice_util(fp_path)
    #         if '' != result.get('number'):
    #             arr = []
    #             arr.append(result.get('number'))
    #             arr.append(result.get('date').replace("年", "-").replace("月", "-").replace("日", ""))
    #             arr.append(fp_path)
    #             return arr
    #         else:
    #             print('OCR识别发票信息数据为空！')